<?php

namespace app\api\controller;

use app\api\model\Code;
use app\api\model\User;
use app\api\model\RecycleReview;
use app\api\model\ConfigSystem as Config;
use think\Db;
use think\Cache;
use GatewayClient\Gateway;
use app\service\Token;
use app\service\UserRepeat;
use app\service\UserDevice;
use app\service\UserWarn;
use app\api\model\Reg as RegModel;
use Vectorface\Whip\Whip;
use app\utils\IpInfoUtils;
use think\Request;

class Login extends Common
{
    
    public function indexold()
{
    $email = input('email', '');
    if (isset($this->params['password'])) {
        if ($email) {
            $user_id = Db::name('user_auth')->where(['account'=>$email, 'type'=>1, 'state'=>1])->value('user_id');
            $user = User::get($user_id);
        } else {
            $user = User::get(['phone' => $this->params['phone'], 'reg' => 1]);
            if (!$user) return $this->return['user.error.notExist'];
        }
        //if ($user['password'] != $this->params['password']) return $this->return['user.error.pwdFail'];
        //进行加密的密码验证
        $inputPassword=$this->params['password'];
        $hashedPassword=$user['password'];
        //echo $inputPassword.'<br/>'.$hashedPassword;die;
        if (!password_verify($inputPassword,$hashedPassword)) {return $this->return['user.error.pwdFail'];}
    } else {
        if (!isset($this->params['code'])) return $this->return['sms.error.code'];
        if ($email) {
            $verify = Code::verifyEmailCode($email, $this->params['code']);
        } else {
            $verify = Code::verifyCode($this->params['phone'], $this->params['code']);
        }

        if ($verify['code'] == 400) {
            return $this->miss($verify['msg'].'0');
        }

        if ($email) {
            $user = Db::name('user')->alias('u')->join('user_auth b', 'u.id=b.user_id')->where(['b.type'=>1,'b.account' => $email, 'b.state' => 1, 'u.reg'=>1])->field('u.*')->find();
        } else {
            $user = User::get(['phone' => $this->params['phone'], 'reg' => 1]);
        }
    }

    if ($user) {

        if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) > time()) {
            $this->allowAccessTo($user);
            //     return $this->miss('账号被封禁，解封时间：' . $user['banned_end_time'],201);
            //     // return $this->return['user.error.blockade'];
        }
        // if ($user['last_login_time'] < strtotime('2023-01-01')) {
        //     return $this->miss('账号已注销');
        // }

        $time = time();

        $updates = [
            'id' => $user['id'],
            // 'is_banned' => 0,
            // 'banned_end_time' => null,
            'is_online' => 1,
            'last_login_datetime' => date('Y-m-d H:i:s'),
            'device_id' => $this->params['device_id'],
            'last_login_time' => $time
        ];


        if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) < time()) {
            $isReadRule = Db::name('config_personal')->where(['user_id'=>$user['id']])->value('is_read_rule');
            if ($isReadRule) {
                $updates['is_banned'] = 0;
                $updates['banned_end_time'] = null;
            }
        }

        //if ($user['remote']) {
        $updates['role'] = 0;
        //}

        User::update($updates);
        if ($user['sex'] == '男' && $user['quality'] != 1 && $updates['last_login_time'] - $user['last_login_time'] >= 7*86400) {
            $this->sysHiChatPush($user['id']);
            // _rabbitMqPublish('action', [
            //     'action' => 'api/Login/sysHiChatPush',
            //     'data'   => ['uid'=>$user['id']]
            // ]);
        }

        if ($this->params['device_id']) {
            $message = json_encode(['code' => 200, 'action' => 'login', 'data' => ['device_id' => $this->params['device_id']]]);
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], $message);

            UserRepeat::InsertS($user['id'], 'device_ids', $this->params['device_id']);
            UserDevice::InsertS($user['id'], $this->params['device_id']);
        }
        UserRepeat::InsertS($user['id'], 'os', $_SERVER['HTTP_USER_AGENT']);

        UserWarn::CheckWarn($user['id'], '登录');

        cache('video_' . $user['id'], NULL);

        // User::bindPrev($user);
        User::welfare($user);
        User::pushchat($user);
        RecycleReview::unRecycle($user['id']);

        $tokenData = array(
            'userid' => $user['id'],
            'time' => $time,
            'sex' => $user['sex']
        );

        $token = Token::createToken($tokenData);
        if($token['status']==200){
            $token = $token['token'];
        }else{
            $token = '';
        }

        try {
            $ip = (new Whip())->getValidIpAddress();
            $ipinfo = IpInfoUtils::info($ip);
            if ($ip && $ipinfo && isset($ipinfo['city'])) {
                $city = substr($ipinfo['city'],0,strrpos($ipinfo['city'],'市'));
                if ($user['city'] && $user['city'] != $city && $user['device_id'] != $this->params['device_id']) {
                    Db::name('user_device_warn')->insert([
                        'user_id'=>$user['id'],
                        'city'=>$city,
                        'city_old'=>$user['city'],
                        'device_id'=>$this->params['device_id'],
                        'device_id_old'=>$user['device_id'],
                        'time'=>$time
                    ]);
                }
            }
        } catch (\Exception $e) {
        }

        return $this->pass(['id' => $user['id'], 'sex' => $user['sex'], 'wanshang' => $user['wanshang'], 'token'=>$token], 'result');
    } else {
        return $this->miss('用户未注册',201);
    }
}

    public function index()
    {
        $email = input('email', '');
        //1.首先查询账号是否已注销  已注销不允许登录
        $olduser = Db::name('user')->where(['phone' => $this->params['phone']])->find();
        if($olduser){
            $delete_time=$olduser['delete_time'];
            if($delete_time){//账号已注销
               return $this->miss('账号已注销');
            }
        }
        // 2. 无上级（yqr为空）的用户禁止登录
        // if (empty($olduser['yqr'])) {
        //     return $this->miss('暂时无法登录');
        // }

        // 3. 步骤1：查询所有超推用户的ID（yqrbind_uid存储的是超推用户ID）
        $superUserIds = Db::name('admin')
            ->where('type', 6)
            ->column('bind_uid'); // 返回超推用户ID数组：[101, 102, ...]

        // 4. 步骤2：根据超推用户ID，查询他们的邀请码（yqm）
        $superInviteCodes = [];
        if (!empty($superUserIds)) {
            $superInviteCodes = Db::name('user')
                ->where('id', 'in', $superUserIds)
                ->column('yqm'); // 返回超推用户的邀请码数组：['code101', 'code102', ...]
        }

        // 5. 检查当前用户是否属于超推团队（含超推自己）
        //$isInSuperTeam = $this->isInSuperTeam($olduser['id'], $superInviteCodes);
        // if (empty($olduser['yqr'])) {
        //     return $this->miss('暂时无法登录');
        // }

        if (isset($this->params['password'])) {
            if ($email) {
                $user_id = Db::name('user_auth')->where(['account'=>$email, 'type'=>1, 'state'=>1])->value('user_id');
                $user = User::get($user_id);
            } else {
                $user = User::get(['phone' => $this->params['phone'], 'reg' => 1]);
                if (!$user) return $this->return['user.error.notExist'];
            }
            //if ($user['password'] != $this->params['password']) return $this->return['user.error.pwdFail'];
            //进行加密的密码验证
            $inputPassword=$this->params['password'];
            $hashedPassword=$user['password'];
            //echo $inputPassword.'<br/>'.$hashedPassword;die;
            if (!password_verify($inputPassword,$hashedPassword)) {return $this->return['user.error.pwdFail'];}
        } else {
            if (!isset($this->params['code'])) return $this->return['sms.error.code'];
            if ($email) {
                $verify = Code::verifyEmailCode($email, $this->params['code']);
            } else {
                $verify = Code::verifyCode($this->params['phone'], $this->params['code']);
            }

            if ($verify['code'] == 400) {
                return $this->miss($verify['msg'].'0');
            }

            if ($email) {
                $user = Db::name('user')->alias('u')->join('user_auth b', 'u.id=b.user_id')->where(['b.type'=>1,'b.account' => $email, 'b.state' => 1, 'u.reg'=>1])->field('u.*')->find();
            } else {
                $user = User::get(['phone' => $this->params['phone'], 'reg' => 1]);
            }
        }

        if ($user) {

            if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) > time()) {
                $this->allowAccessTo($user);
            //     return $this->miss('账号被封禁，解封时间：' . $user['banned_end_time'],201);
            //     // return $this->return['user.error.blockade'];
            }
            // if ($user['last_login_time'] < strtotime('2023-01-01')) {
            //     return $this->miss('账号已注销');
            // }

            $time = time();
            
            $updates = [
                'id' => $user['id'],
                // 'is_banned' => 0,
                // 'banned_end_time' => null,
                'is_online' => 1,
                'last_login_datetime' => date('Y-m-d H:i:s'),
                'device_id' => $this->params['device_id'],
                'last_login_time' => $time
            ];


            if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) < time()) {
                $isReadRule = Db::name('config_personal')->where(['user_id'=>$user['id']])->value('is_read_rule');
                if ($isReadRule) {
                    $updates['is_banned'] = 0;
                    $updates['banned_end_time'] = null;
                }
            }
    
            //if ($user['remote']) {
                $updates['role'] = 0;
            //}

            User::update($updates);
            if ($user['sex'] == '男' && $user['quality'] != 1 && $updates['last_login_time'] - $user['last_login_time'] >= 7*86400) {
                $this->sysHiChatPush($user['id']);
                // _rabbitMqPublish('action', [
                //     'action' => 'api/Login/sysHiChatPush',
                //     'data'   => ['uid'=>$user['id']]
                // ]);
            }

            if ($this->params['device_id']) {
                $message = json_encode(['code' => 200, 'action' => 'login', 'data' => ['device_id' => $this->params['device_id']]]);
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], $message);

                UserRepeat::InsertS($user['id'], 'device_ids', $this->params['device_id']);
                UserDevice::InsertS($user['id'], $this->params['device_id']);
            }
            UserRepeat::InsertS($user['id'], 'os', $_SERVER['HTTP_USER_AGENT']);

            UserWarn::CheckWarn($user['id'], '登录');

            cache('video_' . $user['id'], NULL);

            // User::bindPrev($user);
            User::welfare($user);
            User::pushchat($user);
            RecycleReview::unRecycle($user['id']);

            $tokenData = array(
                'userid' => $user['id'],
                'time' => $time,
                'sex' => $user['sex']
            );

            $token = Token::createToken($tokenData);
            if($token['status']==200){
                $token = $token['token'];
            }else{
                $token = '';
            }

            try {
                $ip = (new Whip())->getValidIpAddress();
                $ipinfo = IpInfoUtils::info($ip);
                if ($ip && $ipinfo && isset($ipinfo['city'])) {
                    $city = substr($ipinfo['city'],0,strrpos($ipinfo['city'],'市'));
                    if ($user['city'] && $user['city'] != $city && $user['device_id'] != $this->params['device_id']) {
                        Db::name('user_device_warn')->insert([
                            'user_id'=>$user['id'],
                            'city'=>$city,
                            'city_old'=>$user['city'],
                            'device_id'=>$this->params['device_id'],
                            'device_id_old'=>$user['device_id'],
                            'time'=>$time
                        ]);
                    }
                }
            } catch (\Exception $e) {
            }

            return $this->pass(['id' => $user['id'], 'sex' => $user['sex'], 'wanshang' => $user['wanshang'], 'token'=>$token], 'result');
        } else {
            return $this->miss('用户未注册',201);
        }
    }
   /**
     * 检查用户是否属于超推团队（核心逻辑）
     */
    private function isInSuperTeam($userId, $superInviteCodes)
    {
        // 获取当前用户的邀请码和上级邀请码
        $user = Db::name('user')->where('id', $userId)->field('yqm, yqr')->find();
        if (empty($user)) {
            return false;
        }

        // 情况1：用户自己是超推（邀请码在超推邀请码列表中）
        if (in_array($user['yqm'], $superInviteCodes)) {
            return true;
        }

        // 情况2：递归检查上级链条是否有超推（最多查10级，避免死循环）
        $currentYqr = $user['yqr']; // 当前用户的上级邀请码

        while (!empty($currentYqr)) {
            // 若上级邀请码是超推的，说明当前用户在超推团队内
            if (in_array($currentYqr, $superInviteCodes)) {
                return true;
            }
            // 继续查询上级的上级邀请码
            $parent = Db::name('user')->where('yqm', $currentYqr)->value('yqr');
            $currentYqr = $parent;
        }

        // 不在超推团队内
        return false;
    }
    public function wechat()
    {
        switch ($this->params['type']) {
            case 1:
                $model = 'qq_openID';
                break;
            case 2:
                $model = 'wb_openID';
                break;
            default:
                $model = 'wechat';
                break;
        }

        $user = User::get([$model => $this->params['wechat'], 'reg' => 1]);

        if (!$user) {
            return $this->pass([
                'user_id' => $this->params['wechat'],
                'name' => $this->params['name'],
                'sex' => $this->params['sex']
            ], 'result', ['state' => 1]);
        } else {
            // if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) > time()) {
            //     return $this->miss('账号被封禁，解封时间：' . $user['banned_end_time'],201);
            //     return $this->return['user.error.blockade'];
            // }
            // if ($user['last_login_time'] < strtotime('2023-01-01')) {
            //     return $this->miss('账号已注销');
            // }

            $time = time();
            
            $updates = [
                'id' => $user->id,
                'is_online' => 1,
                'last_login_datetime' => date('Y-m-d H:i:s'),
                'device_id' => $this->params['device_id'],
                'last_login_time' => $time
            ];
            if ($user->is_banned == 1 && strtotime($user->banned_end_time) < time()) {
                $isReadRule = Db::name('config_personal')->where(['user_id'=>$user->id])->value('is_read_rule');
                if ($isReadRule) {
                    $updates['is_banned'] = 0;
                    $updates['banned_end_time'] = null;
                }
            }
            
            //if ($user['remote']) {
                $updates['role'] = 0;
            //}

            User::update($updates);

            if ($this->params['device_id']) {
                $message = json_encode(['code' => 200, 'action' => 'login', 'data' => ['device_id' => $this->params['device_id']]]);
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user->id, $message);
                UserRepeat::InsertS($user->id, 'device_ids', $this->params['device_id'], $this->params['wechat'], $model == 'wechat' ? 0 : 1);
                UserDevice::InsertS($user['id'], $this->params['device_id']);
            }
            UserWarn::CheckWarn($user->id, '登录');

            cache('video_' . $user->id, NULL);

            // User::bindPrev($user);
            User::welfare($user);
            User::pushchat($user);
            if($model == 'wechat'){
                User::setUnion($user->id, $this->params['wechat'], input('ucode',''));
            }
            RecycleReview::unRecycle($user->id);


            // $this->get_score($user);

            $tokenData = array(
                'userid' => $user->id,
                'time' => $time,
                'sex' => $user->sex
            );
            $token = Token::createToken($tokenData);
            if($token['status']==200){
                $token = $token['token'];
            }else{
                $token = '';
            }

            return $this->pass(['user_id' => $user->id, 'sex' => $user->sex, 'token'=>$token], 'result', ['state' => 0]);
        }
    }

    public function bindOpenid()
    {
        $result = _isMobile($this->params['phone'], 86);
        if ($result['code'] == 400) return $this->miss($result['msg']);

        $verify = Code::verifyCode($this->params['phone'], $this->params['code']);
        if ($verify['code'] == 400) return $this->miss($verify['msg']);

        $user = User::get(['phone' => $this->params['phone'], 'reg' => 1]);
        if (!$user) return $this->return['user.error.notExist'];
        // if ($user && $user['wechat']) return $this->miss('当前手机号已绑定其他那蓝之恋账号，请使用手机验证码登录');

        if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) > time()) {
            return $this->return['user.error.blockade'];
        }

        $time = time();

        $field = $this->params['types'] == 1 ? 'wechat' : 'qq_openID';

        $contain = [
            'id' => $user['id'],
            'role' => 0,
            $field => $this->params['openid'],
            'is_banned' => 0,
            'banned_end_time' => null,
            'last_login_datetime' => date('Y-m-d H:i:s'),
            'device_id' => $this->params['device_id'],
            'last_login_time' => $time
        ];

        User::update($contain);

        if ($this->params['device_id']) {
            RegModel::checkDevice($this->params['device_id'], $user['id']);
            $message = json_encode(['code' => 200, 'action' => 'login', 'data' => ['device_id' => $this->params['device_id']]]);
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], $message);
        }

        cache('video_' . $user['id'], NULL);

        // User::bindPrev($user);
        User::welfare($user);
        User::pushchat($user);
        RecycleReview::unRecycle($user['id']);

        $tokenData = array(
            'userid' => $user['id'],
            'time' => $time,
            'sex' => $user['sex']
        );
        $token = Token::createToken($tokenData);
        if($token['status']==200){
            $token = $token['token'];
        }else{
            $token = '';
        }

        return $this->pass(['id' => $user['id'], 'sex' => $user['sex'], 'wanshang' => $user['wanshang'], 'token' => $token]);
    }

    public function setOnline(Request $request = null)
    {
        $user_id = $this->params['user_id'] ?? 0;
        if (!$user_id) {
            return;
        }

        //action('api/adapay/query_user', ['member_id'=>$user_id]);
        $update = [
            'id' => (int)$user_id,
            // 'is_online' => $this->params['state'],
            'is_online' => 1,
            'last_login_datetime' => date('Y-m-d H:i:s')
        ];
        if ($this->member && $this->member['is_banned'] && strtotime($this->member['banned_end_time'])>time()){
            $update['is_online'] = 0;
        }

        //$logout = input('logout', 0);
        //if($this->params['state'] == 0 && $logout){
        if($this->params['state'] == 0){    
            //$update['last_login_time'] = $logout;
            $update['is_online'] = 0;
        }

        if ($this->params['state']) {
            $day = 0;
            $userTopup = Db::name('user_data')->where(['user_id'=>$user_id])->value('topup');
            if ($userTopup > 350000) {
                $day = 99 * 365;
            } else if ($userTopup > 25000) {
                $day = 730;
            } else if ($userTopup > 15000) {
                $day = 365;
            } else if ($userTopup > 10000) {
                $day = 180;
            } else if ($userTopup > 5000) {
                $day = 90;
            }
            $day=0;//后来不送VIP
            if ($day) {
                $timenow = time();
                $welfareVip = Db::name('welfare_vip')->master()->where(['user_id'=>$user_id, 'type'=>0])->find();
                if (!$welfareVip) {
                    $gradeNoble = Db::name('grade_noble')->find();

                    $userGrade = Db::name('user_noble')->where(['user_id' => $user_id, 'grade' => $gradeNoble['grade']])->find();
                    if ($userGrade) {
                        $viptime = $userGrade['expire'] > $timenow ? $userGrade['expire'] + $day * 86400 : $timenow + $day * 86400;
                        Db::name('user_noble')->where(['id' => $userGrade['id']])->update(['expire' => $viptime, 'update_time' => $timenow]);
                    } else {
                        $viptime = $timenow + $day * 86400;
                        Db::name('user_noble')->insert([
                            'user_id' => $user_id,
                            'grade' => $gradeNoble['grade'],
                            'expire' => $viptime,
                            'create_time' => $timenow,
                            'update_time' => $timenow,
                        ]);
                    }

                    $update['noble_grade'] = $gradeNoble['grade'];
                    $update['noble_time'] = $viptime;
                    Db::name('welfare_vip')->insert([
                        'user_id'   =>  $user_id,
                        'expire_time'   => date('Y-m-d H:i:s', $viptime),
                        'value' => $userTopup,
                        'date'  => date('Y-m-d H:i:s')
                    ]);
                }
            }

            // if ($this->member['sex'] == '男') {
                // $this->systemPushLianmaiMale();
            // }
        }

        $timenow = time();
        // if ($this->params['state'] == 0) {
            $lianmai = Cache::store('redis')->get('lianmaiuser:'.$user_id);
            if ($lianmai) {
                $chat = Db::name('privatechat')->master()->where(['order_id'=>$lianmai])->find();
                if ($chat && strlen($chat['data']) < 1900) {
                    $chatData = json_decode($chat['data'], true);
                    if (!isset($chatData['pending'])) {
                        $chatData['pending'] = [];
                    }
                    $chatData['pending'][$user_id][] = ['t'=>$timenow, 's'=>$this->params['state']];
                    Db::name('privatechat')->where(['id'=>$chat['id']])->update(['data'=>json_encode($chatData, JSON_UNESCAPED_UNICODE)]);
                }
            }
        // }
        $commonRedis =commonRedis();
        $commonRedis->set('user_online:user_is_online_'.$user_id,$update['is_online'],10800);
        User::update($update);
        unset($update['id']);
        if ($this->member && $this->member['reg'] == 1) {
            $privacy_uid = Db::name('user')->where(['reg'=>2, 'authcode'=>$user_id])->cache(3600)->value('id');
        if ($privacy_uid) {
            User::where(['id'=>$privacy_uid])->update($update);
        }

        $setOnlineCacheKey = 'setOnline:'.$user_id.':'.$this->params['state'];
        if (!cache($setOnlineCacheKey)) {
        UserRepeat::InsertS($user_id, 'ips', (new Whip())->getValidIpAddress());
        $app_version = $this->params['app_version'] ?? 0;
        if ($app_version) {
            UserRepeat::InsertS($user_id, 'last_login_app_version', $app_version);
        }


        $device_brand = $this->params['device_brand'] ?? '';
        if ($device_brand) {
            UserRepeat::InsertS($user_id, 'device_brand', $device_brand);
        }

        try {
            $user = Db::name('user')->find($user_id);
            if($this->params['state'] == 1){
                User::welfare($user);
                if($user['sex'] == '女' && !cache('onlineGreet:' . $user['id'])){
                    User::pushchat($user);
                }
                // if(!cache('pushchatUnFirst:' . $user['id'])){
                    User::pushchatUnFirst($user);
                // }
                UserRepeat::InsertS($user['id'], 'os', $_SERVER['HTTP_USER_AGENT']);
            }
            (new \app\service\TencentIM)->account_import($user_id, $user['name'], $user['head_portrait']?:$user['head_100']);
        } catch (\Exception $e) {
            
        }
        cache($setOnlineCacheKey, $update['last_login_datetime'], 60);
        }
        }

        return $this->return['common.success.update'];
    }
    public function systemPushLianmaiMale()
    {
        $config = Config::index('push');
        // 用户版本需达到要求
        $user_app_version = Db::name('user_repeat_check')->where(['user_id'=>$this->member['id']])->value('last_login_app_version');
        if (!$user_app_version || $user_app_version < $config['spl_app_version_lower']) {
            return '';
        }

        // 用户是否开启推送
        $system_video_push_reject = Db::name('config_personal')->where(['user_id'=>$this->member['id']])->value('system_video_push_reject');
        if ($system_video_push_reject) {
            return '';
        }
        $todayPushNum = Db::name('push_lianmai_system')->where(['user_id|touserid'=>$this->member['id'], 'type'=>1])->whereTime('time','today')->count();
        if ($todayPushNum >= $config['spl_day_num']) {
            return '';
        }
        if(Cache::store('redis')->get('lianmaiuser:' . $this->member['id'])) {
            return '';
        }
        if ($this->member['volley'] < 40) {
            return '';
        }
        $topupYesterday = Db::name('topup')
                            ->where(['fk_userid'=>$this->member['id'], 'state'=>1])
                            ->whereTime('addtime','yesterday')
                            ->find();
        if (!$topupYesterday) {
            return '';
        }
        $users = action('api/Privatechat/chatOnline', ['func'=>'systemPushLianmai']);
        $users = json_decode($users->getContent(),true);
        // var_dump($users);exit;
        if (!$users || $users['code'] != 200 || empty($users['data'])) {
            return '';
        }

        $touserid = $users['data'][rand(0, sizeof($users['data'])-1)]['id'];
        $client = getenv('SOCKET_PREFIX') . $touserid;
        if(sizeof(Gateway::getClientIdByUid($client)) == 0){
            return '';
        }

        $user = Db::name('user')->find($touserid);
        $result = action('api/Member/checkMic', ['to_user' => $this->member['id'],'types' => 2,'auto' => 1, 'user'=>$user]);
        $result = json_decode($result->getContent(),true); 
        // var_dump($result);exit;
        if ($result['code'] == 200) {
            $orderid = $result['data']['orderid'];
            $message = json_encode([
                'code' => 200,
                'action' => 'systemPushLianmai',
                'data' => ['another_id'=>$this->member['id'], 'types'=>2, 'orderid'=>$orderid]
            ]);
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $message);
            Db::name('push_lianmai_system')->insert(['user_id'=>$this->member['id'], 'touserid'=>$touserid, 'type'=>1, 'order_id'=>$orderid, 'time'=>time()]);
        }
    }
    public function systemPushLianmaiFemale()
    {
        // 用户版本需达到要求
        $config = Config::index('push');
        $user_app_version = Db::name('user_repeat_check')->where(['user_id'=>$this->member['id']])->value('last_login_app_version');
        if (!$user_app_version || $user_app_version < $config['spl_app_version_lower']) {
            return '';
        }

        // 用户是否开启推送
        $system_video_push_reject = Db::name('config_personal')->where(['user_id'=>$this->member['id']])->value('system_video_push_reject');
        if ($system_video_push_reject) {
            return '';
        }
        $PushNum = Db::name('push_lianmai_system')->where(['user_id'=>$this->member['id'], 'type'=>1])->find();
        if ($PushNum) {
            return '';
        }
        if(Cache::store('redis')->get('lianmaiuser:' . $this->member['id'])) {
            return '';
        }
        $users = action('api/Privatechat/chatOnlineMale', ['func'=>'systemPushLianmai']);
        $users = json_decode($users->getContent(),true);
        if (!$users || $users['code'] != 200 || empty($users['data'])) {
            return '';
        }
        $touserid = $users['data'][rand(0, sizeof($users['data'])-1)]['id'];
        $result = action('api/Member/checkMic', ['to_user' => $touserid,'types' => 2,'auto' => 1, 'user'=>$this->member]);
        $result = json_decode($result->getContent(),true); 
        if ($result['code'] == 200) {
            $orderid = $result['data']['orderid'];
            $message = json_encode([
                'code' => 200,
                'action' => 'systemPushLianmai',
                'data' => ['another_id'=>$touserid, 'types'=>2, 'orderid'=>$orderid]
            ]);
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $this->member['id'], $message);
            Db::name('push_lianmai_system')->insert(['user_id'=>$this->member['id'], 'touserid'=>$touserid, 'type'=>1, 'order_id'=>$orderid, 'time'=>time()]);
        }
    }

    public function fast($token, $method = 0)
    {
        $url = 'https://api.253.com/open/flashsdk/mobile-query';

        $appId = $method ? getenv('SHANYAN_APPID_IOS') : getenv('SHANYAN_APPID_ANDROID');
        $appKey = $method ? getenv('SHANYAN_APPKEY_IOS') : getenv('SHANYAN_APPKEY_ANDROID');

        $outId = '';
        $clientIp = '';
        $encryptType = '0';

        $content = 'appId' . $appId . 'clientIp' . $clientIp . 'encryptType' . $encryptType . 'outId' . $outId . 'token' . $token;
        $sign = bin2hex(hash_hmac('sha256', $content, $appKey, true));

        $params = [
            'appId' => $appId,
            'token' => $token,
            'outId' => $outId,
            'clientIp' => $clientIp,
            'encryptType' => $encryptType,
            'sign' => $sign
        ];

        // CURL 模拟 post 请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $resultJson = curl_exec($ch);
        $curlInfo = curl_getinfo($ch);

        // CURL 错误码
        $errNo = curl_errno($ch);
        if ($errNo > 0) {
            // 通信失败处理逻辑，请自己填充

            // CURL 错误信息
            $errMsg = curl_error($ch);
            // TODO
            return json(['code' => 400, 'msg' => $errMsg]);
        } elseif (!empty($curlInfo) && intval($curlInfo['http_code']) != 200) {
            // http 状态码不是 200，请求失败处理逻辑
            $httpCode = $curlInfo['http_code'];
            // TODO
            return json(['code' => 400, 'msg' => '请求失败，状态码:' . $httpCode]);
        } else {
            // 拿到请求结果，使用返回结果逻辑
            $requestData = json_decode($resultJson, true);
            if ($requestData['code'] == 200000) {
                $chargeStatus = $requestData['chargeStatus']; // 是否收费，枚举值：1 ：收费 0：不收费
                $mobile = $requestData['data']['mobileName']; // 手机号

                if ('0' == $encryptType) { //AES解密 ，默认方式
                    $key = md5($appKey);
                    $mobile = openssl_decrypt(hex2bin($mobile), 'AES-128-CBC', substr($key, 0, 16), OPENSSL_RAW_DATA, substr($key, 16));
                    // 如解密失败 请检查$appKey是否正确
                }

                $tradeNo = $requestData['data']['tradeNo']; // 流水号
                // 拿到返回数据继续处理逻辑 TODO
                if ($mobile) {
                    $user = Db::name('user')->field('id, sex, wanshang, role, is_banned, banned_end_time, remote')->where(['phone' => $mobile])->find();

                    if (!$user) return json(['code' => 300, 'msg' => $mobile]);

                    if ($user['is_banned'] == 1 && strtotime($user['banned_end_time']) > time()) {
                        return json(['code' => 400, 'msg' => '账号封至' . $user['banned_end_time']]);
                    }
                    
                    $updates = [
                        'id' => $user['id'],
                        'is_banned' => 0,
                        'banned_end_time' => null,
                        'is_online' => 1,
                        'last_login_datetime' => date('Y-m-d H:i:s'),
                        'device_id' => $this->params['device_id'],
                    ];
    
                    //if ($user['remote']) {
                        $updates['role'] = 0;
                    //}

                    User::update($updates);

                    if ($this->params['device_id']) {
                        $message = json_encode(['code' => 200, 'action' => 'login', 'data' => ['device_id' => $this->params['device_id']]]);
                        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], $message);
                    }

                    cache('video_' . $user['id'], NULL);

                    // User::bindPrev($user);
                    User::welfare($user);
                    User::pushchat($user);
                    RecycleReview::unRecycle($user['id']);

                    return json(['code' => 200, 'msg' => '登陆成功', 'result' => ['id' => $user['id'], 'sex' => $user['sex'], 'wanshang' => $user['wanshang']]]);
                } else {
                    return json(['code' => 400, 'msg' => '无法获取手机号']);
                }
            } else {
                // 响应异常处理逻辑 TODO
                return json(['code' => 400, 'msg' => $requestData['message']]);
            }
        }
    }

    // app 从后台切回前台时检测是否有被其它设备挤下线
    public function checkLogin()
    {
        if ($this->member['device_id'] && $this->params['device_id'] && $this->member['device_id'] != $this->params['device_id']) {
            return $this->return['login.error.loginOut'];
        } else {
            return $this->return['login.success.default'];
        }
    }

    public function sysHiChatPush($uid = 0)
    {
        if (!$uid) return false;
        $user = Db::name('user')->find($uid);
        if (!$user) return false;
        if ($user['reg'] != 1 || $user['sex'] != '男' || $user['quality'] == 1) return false;
        $userData = Db::name('user_data')->where(['user_id'=>$uid])->find();
        if ($userData && $userData['topup']>=20000) return false;

        $intimateWhere = [['between',[100,5000]], ['between',[0.1,100]]];
        $num = 0;
        while (isset($intimateWhere[$num])) {
            $touser = Db::name('user_intimate')->where(['intimate'=>$intimateWhere[$num], 'unshow'=>0])->where("find_in_set($uid, couple_a)")->column('couple_a');
            if (empty($touser)) {
                $num++;
                continue;
            }
            $uids = [];
            foreach ($touser as $key => $value) {
                $couple = explode(',', $value);
                $uids[] = $couple[0] == $uid ? $couple[1] : $couple[0];
            }
            $blacklist1 = Db::name('blacklist')
                    ->where(['user_id'=>$uid, 'to_user'=>['in', $uids]])
                    ->column('to_user');
            $blacklist2 = Db::name('blacklist')
                    ->where(['user_id'=>['in', $uids], 'to_user'=>$uid])
                    ->column('user_id');
            $uids = array_diff($uids, $blacklist1, $blacklist2);
            $users = Db::name('user')->where(['id'=>['in', $uids], 'sex'=>'女', 'quality'=>['>',1], 'is_banned'=>0, 'delete_time'=>0, 'last_login_datetime'=>['>=', date('Y-m-d H:i:s', strtotime('-7 day'))]])->whereTime('last_login_datetime', '-7 day')->order('last_login_datetime desc')->limit(3)->field('id,name,sex,realname_auth')->select();
            if (sizeof($users)) {
                $num = -1;
                $url = 'http://' . getenv('APP_URL') . '/apis/home/privatechat/addtalk';
                $contents = Db::name('privatechat_zhaohu')->where(['types' => 2, 'is_hidden' => 0])->cache('systemzhaohuall',86400)->column('content');
                foreach ($users as $key => $value) {
                    $rand = mt_rand(0, count($contents) - 1);
                    $data = [
                        'userid' => $value['id'],
                        'touserid' => $uid,
                        'content' => $contents[$rand],
                        'timing' => 1,
                        'greet' => 1,
                        'single' => $value['realname_auth'] > 0 ? 0 : 2,
                        'notice' => 1,
                        'quality'=> 1
                    ];

                    sendcurl($url, json_encode($data, JSON_UNESCAPED_UNICODE));
                }
            } else {
                $num++;
            }
        }
    }
}